package com.lagou.dao;

import com.lagou.entity.Category;
import com.lagou.entity.Product;
import com.lagou.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

public class ProductDao {
    public Product findProducById(String id) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.dataSource);

        String sql = "select * from product where pid = ?";

        Product product = queryRunner.query(sql, new BeanHandler<Product>(Product.class), id);
        String cid = product.getCid();
        Category category = findCategoryById(cid);
        product.setCategory(category);
        return product;

    }

    public Category findCategoryById(String id) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.dataSource);
        String sql = "select * from category where cid = ?";
        Category category = queryRunner.query(sql, new BeanHandler<Category>(Category.class), id);
        return category;
    }

    public int getCount(String cid) throws SQLException {
        QueryRunner qr = new QueryRunner(DruidUtils.dataSource);
        String sql = "select count(*) from product where cid =  ?";
        Long l = qr.query(sql, new ScalarHandler<>(), cid);
        return  l.intValue();
    }
    public List<Product> findProductByCid(String cid) throws SQLException {
        QueryRunner qr = new QueryRunner(DruidUtils.dataSource);
        String sql = "select* from product where cid =  ?";
        List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class), cid);
        return list;
    }

}
